package com.luozhili.rabbitmqlearningdemo.topic_demo;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Recv {
    private final static String QUEUE_NAME = "topic_learn_queue_2";
    private final static String EXCHANGE_NAME = "topic_learn_exchange_1";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.31.226");
        factory.setUsername("zhangsan");
        factory.setPassword("123456");
        factory.setVirtualHost("/shopping");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();


        //声明队列 （在订阅模式中，发送者创建路由器后 订阅者在订阅路由器后创建队列）
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        //将创建的队列 与 路由器绑定
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"user.*");
        System.out.println(" [*] 等待消息 ... " );


        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body);
                System.out.println(" [x] 接收消息 '" + message + "'");

                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };

        channel.basicConsume(QUEUE_NAME, false, consumer);

    }
}
